import {View, Text, Button} from "@tarojs/components";
import React, {useReducer} from 'react';
import { getCurrentInstance } from '@tarojs/taro';

/* 使用 useReducer 01 */
// const initialState = {count:0};
// function reducer(state,action) {
//   switch (action.type) {
//     case 'increment':
//       console.log(`old count is ${state.count}`);
//       console.log(`new count is ${state.count + 1}`);
//       return {count:state.count + 1};
//     case 'decrement':
//       console.log(`old count is ${state.count}`);
//       console.log(`new count is ${state.count - 1}`);
//       return {count:state.count - 1};
//     default:throw new Error('underfind type');
//   }
// }
/* 使用 useReducer 02 */
function init(initialCount) {
  return {count:initialCount};
}
function reducer(state,action) {
  switch (action.type) {
    case 'reset':return {count:action.payload};
    case 'increment':return {count:state.count +1};
    case 'decrement':return {count:state.count - 1};
    default:throw new Error();
  }
}
function HookApi() {

  // @ts-ignore
  const initialCount = Number(getCurrentInstance().router.params.initialCount || 0);
  // const [count, setCount] = useState(initialCount);

  const [state,dispatch] = useReducer(reducer, initialCount,init);
  console.log(`initial count is ${initialCount}`);
  console.log('render : count is ' + state.count);
  return (
    <View>
      <Text> Count : {state.count} </Text>
      {/* //使用useState */}
      {/*<button onClick={() => setCount(initialCount)}>Reset</button>*/}
      {/*<Button onClick={() => setCount((prevCount) => prevCount - 1)}>-</Button>*/}
      {/*<Button onClick={() => setCount((prevCount) => prevCount + 1)}>+</Button>*/}
      {/*{// 使用useReducer 01}*/}
      {/*<Button onClick={()=>dispatch({type:'increment'})}>+</Button>*/}
      {/*<Button onClick={()=>dispatch({type:'decrement'})}>-</Button>*/}
      {/*{// 使用 useReducer 02 }*/}
      <Button onClick={()=> dispatch({type:'reset',payload:initialCount})}>reset</Button>
      <Button onClick={()=> dispatch({type:'increment'})}>+</Button>
      <Button onClick={()=> dispatch({type:'decrement'})}>-</Button>
    </View>
  );
}

export default HookApi;
